package cn.itsource.pethome.utils;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.IOException;

public enum SmsUtils {

    INSTANCE;

    private SmsUtils(){}

    /**
     * 发送短信
     * Java程序发送http请求：
     *  1）JDK底层的java.net包内的HttpUrlConnection
     *  2）apache的commons-httpclient
     *  3）糊涂的hutool的HttpUtils工具类
     * @param phone     接收短信的手机号
     * @param content   短信内容
     */
    public void send(String phone, String content){
        try {
            HttpClient client = new HttpClient();
            PostMethod post = new PostMethod("http://utf8.api.smschinese.cn");

            //在头文件中设置转码
            post.addRequestHeader("Content-Type",
                    "application/x-www-form-urlencoded;charset=utf-8");

            //封装请求参数
            NameValuePair[] data = {
                    new NameValuePair("Uid", "xyz123456"),
                    new NameValuePair("Key", "d41d8cd98f00b204e980"),
                    new NameValuePair("smsMob", phone),
                    new NameValuePair("smsText", content)};
            //将请求参数设置到请求的消息体中
            post.setRequestBody(data);
            //执行调用：发送请求
            client.executeMethod(post);

            //响应头
            Header[] headers = post.getResponseHeaders();
            int statusCode = post.getStatusCode();
            System.out.println("statusCode:"+statusCode);
//            for(Header h : headers){
//                System.out.println(h.toString());
//            }

            //获取响应消息
            String result = new String(post.getResponseBodyAsString().getBytes("utf-8"));
            //打印返回消息
            System.out.println(result);

            //释放连接
            post.releaseConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
